/*
 *  Copyright (C) 2011  Clint Priest
 *
 *  This file is part of pklib.
 *
 *  pklib is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  pklib is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with pklib.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Portions borrowed or re-written from prototype
 */
 
var Selector = Class.create({
	
} );

Object.extend(Selector, {
	handlers: {
		mark: function(nodes) {
			for (var i = 0, node; node = nodes[i]; i++)
				node._countedByPrototype = true;
			return nodes;
		},

		unmark: function(nodes) {
			for (var i = 0, node; node = nodes[i]; i++)
				delete node._countedByPrototype;
			return nodes;
		},
		
		nextElementSibling: function(node) {
			while (node = node.nextSibling) {
				if (node.nodeType == 1)
					return node;
			}
			return null;
		},

		previousElementSibling: function(node) {
			while (node = node.previousSibling) {
				if (node.nodeType == 1)
					return node;
			}
			return null;
		},
	},
	
	matchElements: function(elements, expression) {
		var doc = document;
		if(doc.location.href.indexOf('chrome') != -1)
			doc = doc.getElementById('content').contentDocument;
		var matches = doc.querySelectorAll(expression), h = Selector.handlers;
		h.mark(matches);
		for (var i = 0, results = [], element; element = elements[i]; i++) {
			if (element._countedByPrototype)
				results.push(element);
		}
		h.unmark(matches);
		return results;
	},

	findElement: function(elements, expression, index) {
		if (Object.isNumber(expression)) {
			index = expression; expression = false;
		}
		return Selector.matchElements(elements, expression || '*')[index || 0];
	},
} );